import { useRef, useState } from 'react';
import { ProTable } from '@ant-design/pro-components';
import { Modal, message, Form, Input } from 'antd';
import { history } from 'umi';
import { PageContainer } from '@ant-design/pro-components';
import { activatecodeSearch, storeActivate, unlockActivate } from '@/services/sensitizeManage';

import type { ParamsType } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-table';
import type { PaginationProps, FormInstance } from 'antd';
import type { ActionType } from '@ant-design/pro-components';

import styles from './style.less';

const { confirm } = Modal;

const SensitizeManageList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [modalForm] = Form.useForm();

  const [confirmLoad, setConfirmLoad] = useState<boolean>(false);
  const [modelVisible, setModelVisible] = useState<boolean>(false);

  // 提交
  const handleOperate = (record: any, type: string) => {
    if (type === '代店激活') {
      modalForm.setFieldValue('id', record.id);
      setModelVisible(true);
      return;
    }

    confirm({
      content: `确认${type} 激活码：${record.activeCode}？`,
      async onOk() {
        if (type === '锁定恢复') {
          try {
            const { code, data } = await unlockActivate({ id: record.id });
            if (code === 200 && data) {
              message.success('操作成功');
              actionRef?.current?.reloadAndRest?.();
            } else {
              message.error('解锁失败');
            }
          } catch (error) {}
        }
      },
      onCancel() {},
    });
  };

  // 跳编辑页
  const hanldleEdit = (record: any) => {
    history.push(`/profile/sensitizeManage/modify/${record.id}`);
  };

  const columns: ProColumns<API.ProfileListItem>[] = [
    // 表单
    {
      title: '激活码',
      dataIndex: 'activeCode',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
      },
    },
    {
      title: '兑换码',
      dataIndex: 'couponCode',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
      },
    },
    {
      title: '活动Id',
      dataIndex: 'activityId',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
      },
    },
    // 表格
    {
      title: '激活码',
      dataIndex: 'activeCode',
      ellipsis: true,
      width: 160,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '兑换码',
      dataIndex: 'couponCode',
      ellipsis: true,
      width: 120,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '活动Id',
      dataIndex: 'activityId',
      ellipsis: true,
      width: 180,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '批次ID',
      dataIndex: 'groupId',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '激活码状态',
      dataIndex: 'activieCodeStatus',
      ellipsis: true,
      width: 100,
      align: 'center',
      hideInSearch: true,
      valueEnum: {
        0: { text: '可激活' },
        1: { text: '已激活' },
        2: { text: '销毁' },
        3: { text: '锁定' },
      },
    },
    {
      title: '激活用餐厅号',
      dataIndex: 'storeId',
      ellipsis: true,
      width: 120,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '激活用订单号',
      dataIndex: 'orderId',
      ellipsis: true,
      width: 180,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '收银机售卖产品ID',
      dataIndex: 'productId',
      ellipsis: true,
      width: 130,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '锁定时间',
      dataIndex: 'lockedTime',
      ellipsis: true,
      width: 150,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '激活码时间',
      dataIndex: 'activedTime',
      ellipsis: true,
      width: 150,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '最后更新时间',
      dataIndex: 'lastUpdateTime',
      ellipsis: true,
      width: 150,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: 200,
      align: 'center',
      hideInSearch: true,
      fixed: 'right',
      render(_, record) {
        return (
          <div key={record.id}>
            <a onClick={() => hanldleEdit(record)}>修改</a>&nbsp;&nbsp;
            {/* 销毁 已激活 锁定 */}
            {['已激活', '销毁', '锁定'].includes(record.activieCodeStatusStr) ? (
              <span style={{ color: 'darkgray' }}>代店激活</span>
            ) : (
              <a onClick={() => handleOperate(record, '代店激活')}>代店激活</a>
            )}
            &nbsp;&nbsp;
            {record.activieCodeStatus !== 3 ? (
              <span style={{ color: 'darkgray' }}>锁定恢复</span>
            ) : (
              <a onClick={() => handleOperate(record, '锁定恢复')}>锁定恢复</a>
            )}
            &nbsp;&nbsp;
          </div>
        );
      },
    },
  ];

  // 获取列表
  const getPromotionList = async (params: ParamsType) => {
    const { current, ...rest } = params;
    const param: API.ActivatecodeSearchInfo = {
      pageNo: current || 1,
      pageSize: params.pageSize || 10,
      ...rest,
    };

    const { code, data } = await activatecodeSearch(param);
    if (code === 200 && data) {
      const { rows, totalCount, pageSize, pageNo } = data;
      return {
        total: totalCount,
        pageSize,
        current: pageNo,
        data: rows,
      };
    }
    return {};
  };

  const showTotal: PaginationProps['showTotal'] = (t) => `共 ${t} 条`;

  const handleOK = () => {
    modalForm.validateFields().then(async (values) => {
      setConfirmLoad(true);
      const { code, data } = await storeActivate({
        ...values,
      });
      if (code === 200 && data) {
        message.success('操作成功');
        modalForm.resetFields();
        setModelVisible(false);
        actionRef?.current?.reloadAndRest?.();
      }
      setConfirmLoad(false);
    });
  };

  const handleCancel = () => {
    setModelVisible(false);
    modalForm.resetFields();
  };

  return (
    <PageContainer>
      <div className={styles['form-body']}>
        <ProTable<API.ActivatecodeListItem>
          rowKey="id"
          columns={columns}
          actionRef={actionRef}
          formRef={formRef}
          request={getPromotionList}
          options={false}
          search={{
            optionRender: (searchConfig, props, dom) => [...dom],
          }}
          scroll={{ x: 800 }}
          pagination={{
            showSizeChanger: true,
            size: 'small',
            showTotal,
            showQuickJumper: true,
            defaultPageSize: 10,
          }}
        />

        <Modal
          title="代店激活"
          width={520}
          open={modelVisible}
          onOk={handleOK}
          onCancel={handleCancel}
          confirmLoading={confirmLoad}
        >
          <Form
            labelCol={{ span: 6 }}
            form={modalForm}
            initialValues={{
              id: '',
              storeId: '',
              orderId: '',
              productPrice: '',
              productId: '',
            }}
          >
            <Form.Item label="id" name="id" hidden={true}>
              <Input />
            </Form.Item>

            <Form.Item
              label="门店号"
              name="storeId"
              rules={[
                {
                  required: true,
                  message: '不得为空',
                },
              ]}
            >
              <Input placeholder="storeId(必填)" />
            </Form.Item>
            <Form.Item
              label="订单号"
              name="orderId"
              rules={[
                {
                  required: true,
                  message: '不得为空',
                },
              ]}
            >
              <Input placeholder="orderId(必填)" />
            </Form.Item>
            <Form.Item label="订单单价(单位分)" name="productPrice">
              <Input placeholder="Price(没配的,可不填)" />
            </Form.Item>
            <Form.Item label="产品ID" name="productId">
              <Input placeholder="productId(没配的,可不填)" />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </PageContainer>
  );
};

export default SensitizeManageList;
